﻿using AutoMapper;
using MediatR;
using SqlSugar;
using WarehouseManagement.Application.Command.ShipApplyCommand;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;
namespace WarehouseManagement.Application.CommandHandler.ShipApplyCommandHandlers
{
    public class CreateShipCommandHandlers:IRequestHandler<CreateShipCommand,int>
    {
        private readonly IShipRequestRepository _shipRequest;
        private readonly IShipRequestProRepository _shipRequestPro;
        private readonly IMapper _mapper;
        ISqlSugarClient db;


        public CreateShipCommandHandlers(IShipRequestRepository shipRequest, IShipRequestProRepository shipRequestPro, IMapper mapper, ISqlSugarClient db)
        {
            _shipRequest = shipRequest;
            _shipRequestPro = shipRequestPro;
            _mapper = mapper;
            this.db = db;
        
        }

        public async Task<int> Handle(CreateShipCommand request, CancellationToken cancellationToken)
        {
            db.Ado.BeginTran();
            try
            {

                var res = _mapper.Map<ShippRequestApp>(request.Adddto);
                res.ShipState = 1;
                var code = DateTime.Now.ToString("yyyyMMddHHmmss");
                res.SRANumber = $"FH{code}";
                var query = await _shipRequest.AddAsync(res);


                foreach(var item  in request.Adddto.detail)
                {
                    ShipProductApp shipProduct = new ShipProductApp()
                    {
                        ShipProductAppId = item.ShipProductAppId,
                        SRANumber = res.SRANumber,
                        ProductId = item.ProductId,
                        PackMethod = item.PackMethod,
                        Remark = item.Remark,
                        AddName = item.AddName,
                        AddTime = item.AddTime,
                        User_Id = item.User_Id,
                        Office_Id = item.Office_Id,
                        PName = item.PName,
                        PNumber = item.PNumber,
                        ProNum = item.ProNum,
                        PSpec = item.PSpec,
                        PUnit = item.PUnit,

                    };
                    var query2 = await _shipRequestPro.AddAsync(shipProduct);
                }


                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
